package com.codes.config.transaction;

import org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Component;
import org.springframework.transaction.interceptor.TransactionInterceptor;

import javax.sql.DataSource;
import java.util.Properties;


@Configuration    //全局事物      service层  接口实现类  以 Impl  impl  结尾 即可使用事物
//@Component
public class TransactionCommon {
    @Autowired(required = false)
    public DataSourceTransactionManager transactionManager;
    @Autowired
    DataSource dataSource;
    // 创建事务通知
    @Bean(name = "txAdvice")
    public TransactionInterceptor getAdvisor() throws Exception {
        Properties properties = new Properties();
        properties.setProperty("get*", "PROPAGATION_REQUIRED,readOnly");
        properties.setProperty("select*", "PROPAGATION_REQUIRED,readOnly");
        properties.setProperty("count*", "PROPAGATION_REQUIRED,readOnly");
        properties.setProperty("add*", "PROPAGATION_REQUIRED,-Throwable");
        properties.setProperty("save*", "PROPAGATION_REQUIRED,-Throwable");
        properties.setProperty("insert*", "PROPAGATION_REQUIRED,-Throwable");
        properties.setProperty("update*", "PROPAGATION_REQUIRED,-Throwable");
        properties.setProperty("delete*", "PROPAGATION_REQUIRED,-Throwable");
        properties.setProperty("del*", "PROPAGATION_REQUIRED,-Throwable");
        // 所有方法都走事物 .

        TransactionInterceptor tsi = new TransactionInterceptor(transactionManager,properties);
        return tsi;
    }
    @Bean
    public BeanNameAutoProxyCreator txProxy() {
        BeanNameAutoProxyCreator creator = new BeanNameAutoProxyCreator();
        creator.setInterceptorNames("txAdvice");
        creator.setBeanNames("*SV","*Service", "*Impl","*impl");
        creator.setProxyTargetClass(true);
        return creator;
    }
    // 只是一行注释
}
